import { useState, useEffect } from 'react';
import { connect } from 'umi';
import { Select } from 'antd';
import { TRCheckboxModal, TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { fetchUsedUnit } from '@/pages/Tianji/TenDaysCentralizedBidding/services';

/**
 * 选择交易单元组件
 * 此组件封装存在问题，暂时只支持集中竞价功能使用
 */
// 此函数组件主要用于从接口获取数据并处理数据
function SelectStations({
  currentProgramId,
  currentProgramInfo,
  stations,
  selectedUnitIds,
  tradeSeqId,
  stationTree,
  dispatch,
  formData,
}) {
  const title = '交易单元';
  const isEmpty = !stationTree.length;

  const [options, setOptions] = useState([]);

  useEffect(() => {
    let newStations = JSON.parse(JSON.stringify(stations));
    if (!currentProgramInfo.editPermission) {
      let arr = [];
      currentProgramInfo?.unitList?.forEach((item) => {
        let obj = {
          value: item.id + '',
          label: item.stationTitle,
        };
        arr.push(obj);
      });
      newStations = arr;
    }
    newStations = newStations.map((item) => {
      return {
        ...item,
        disabled: true,
      };
    });
    setOptions(newStations);
  }, [currentProgramInfo.unitList]);

  const setUsedUnit = (usedUnitList) => {
    let data = JSON.parse(JSON.stringify(stationTree));
    data.forEach((company) => {
      let isUsedNum = 0;
      (company?.children || []).forEach((station) => {
        // 遍历 usedUnitList，如果当前交易单元在usedUnitList中存在，并且交易单元所属方案与当前方案不同，则禁用当前交易单元
        let isUsed = usedUnitList.filter((item) => {
          return (
            item.unitId + '' === station.value + '' && item.programId + '' !== currentProgramId + ''
          );
        })[0];
        if (isUsed) {
          station.disabled = true;
          station.label = station.label + ' (' + isUsed.programTitle + ')';
          isUsedNum++;
        }
      });
      if (isUsedNum === company?.children?.length) {
        company.disabled = true;
      }
    });
    return data;
  };

  const onHandleModal = async () => {
    if (isEmpty) {
      TRMessage.warning('您没有场站权限，请联系管理员获取相关权限');
      return;
    }

    dispatch({
      type: 'tenDaysCentralizedBidding/setAddLoadingNum',
    });
    const _tradeSeqId = tradeSeqId.includes('PHBSX') ? tradeSeqId : formData?.marketId + tradeSeqId;
    const res = await fetchUsedUnit(_tradeSeqId);
    dispatch({
      type: 'tenDaysCentralizedBidding/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let usedUnitList = res.data.unitList;

      let treeData = setUsedUnit(usedUnitList);

      const result = await TRCheckboxModal.show({
        title,
        value: selectedUnitIds,
        treeData,
        okText: '确认',
      });

      if (result?.index === 1) {
        dispatch({
          type: 'tenDaysCentralizedBidding/setSelectedUnitIds',
          payload: result.checkedKeys,
        });
        dispatch({
          type: 'tenDaysCentralizedBidding/setHasModified',
          payload: true,
        });
      }
      TRCheckboxModal.dismiss();
    } else {
      TRMessage.error(res?.message || '获取指定序列下已有方案的交易单元列表失败');
    }
  };

  return (
    <Select
      value={selectedUnitIds}
      style={{ width: 190 }}
      options={options}
      placeholder={title}
      mode="multiple"
      maxTagCount={1}
      maxTagTextLength={selectedUnitIds.length > 1 ? 2 : 8}
      open={false}
      showSearch={false}
      showArrow={true}
      onClick={onHandleModal}
    />
  );
}

export default connect(({ tenDaysCentralizedBidding }) => ({
  currentProgramId: tenDaysCentralizedBidding.currentProgramId,
  currentProgramInfo: tenDaysCentralizedBidding.currentProgramInfo,
  stations: tenDaysCentralizedBidding.stations,
  selectedUnitIds: tenDaysCentralizedBidding.selectedUnitIds,
  tradeSeqId: tenDaysCentralizedBidding.tradeSeqId,
  stationTree: tenDaysCentralizedBidding.stationTree,
  formData: tenDaysCentralizedBidding.formData,
}))(SelectStations);
